package com.micro.fast.gateway.filter;

import com.micro.fast.boot.starter.common.response.ServerResponse;
import com.micro.fast.gateway.jwt.ValidateJwtToken;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 对accessToken进行校验
 * @author lsy
 */
@Component
public class PreRequestFilter extends ZuulFilter {

    @Value("${jwt.signingKey:msjwt}")
    private String signingKey;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        //校验登录状态和访问权限
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        ServerResponse validate = ValidateJwtToken.validate(request, signingKey);
        if (validate.isSuccess()) {
            //todo  对访问权限进行判断
            // 对请求进行后续处理
            requestContext.setSendZuulResponse(true);
        }else {
            String remoteHost = request.getRemoteHost();
            if (remoteHost.equals("127.0.0.1")){
                // 对本地请求不过滤
                requestContext.setSendZuulResponse(true);
            }else {
                // 不进行后续操作,返回401状态码
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }
        }
        return null;
    }
}
